//
//  Monitoring.swift
//  iBeacon
//
//  Created by 郭颢源 on 2021/4/8.
//

import UIKit
import CoreLocation
/// 监听
class Monitoring: UIViewController, CLLocationManagerDelegate {
    
    fileprivate var beaconRegion: CLBeaconRegion!
    fileprivate var locationManager: CLLocationManager!
    fileprivate var region:CLBeaconIdentityConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        locationManager = CLLocationManager()
        locationManager.delegate = self
       //请求一直允许定位
        locationManager.requestAlwaysAuthorization()
//        beaconRegion = CLBeaconRegion(proximityUUID: UUID(uuidString: "174232B6-F53E-49DA-A32C-224016982580")!, identifier: beaconIdentifier)
        beaconRegion = CLBeaconRegion(uuid: UUID(uuidString: "174232B6-F53E-49DA-A32C-224016982580")!, identifier: beaconIdentifier)
        beaconRegion.notifyEntryStateOnDisplay = true
        //开始扫描
        locationManager.startMonitoring(for: beaconRegion)
//        locationManager.startRangingBeacons(in: beaconRegion)
        region = CLBeaconIdentityConstraint(uuid: UUID(uuidString: "174232B6-F53E-49DA-A32C-224016982580")!)
        locationManager.startRangingBeacons(satisfying: region)
        
    }
    
    //进入beacon区域
        func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
            locationManager.startRangingBeacons(in: beaconRegion)
            print( "进入beacon区域")
        }
        
        //离开beacon区域
        func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
            locationManager.stopRangingBeacons(in: beaconRegion)
            
            print("离开beacon区域")
        }
        
        func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
            //返回是扫描到的beacon设备数组，这里取第一个设备
            guard beacons.count > 0 else { return }
            let beacon = beacons.first!
            //accuracy可以获取到当前距离beacon设备距离
            let location = String(format: "%.3f", beacon.accuracy)
            print( "距离beacon\(location)m")
        }
        
        func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
            print("Failed monitoring region: \(error.localizedDescription)")
        }
        
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print("Location manager failed: \(error.localizedDescription)")
        }

}
